//
//  EventTableViewCell.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/11/2.
//

import UIKit
import HandyJSON

/// 动态cell
class EventTableViewCell: UITableViewCell {

    @IBOutlet weak var userImageView: UIImageView!
    
    @IBOutlet weak var createdDateLabel: UILabel!
    
    @IBOutlet weak var eventTitleLabel: UILabel!
    
    @IBOutlet weak var contentLabel: UILabel!
    
    var model:EventMdoel?{
        didSet{
            guard let m = model else {
                return
            }
            
            let url = m.author?.portrait_url ?? m.author?.new_portrait
            
            if let icon = URL(string: url ?? "") {
                userImageView.kf.setImage(with: icon, placeholder: UIImage(named: "image_loading"), options: .none, progressBlock: nil, completionHandler: nil)
            }
            
            self.eventTitleLabel.attributedText = m.getEventDescriptionForEvent()
            self.setAbstractContent(event: m)
            self.createdDateLabel.text = m.created_at.intervalSinceNow()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        initImageView()
        
    }
    
    func initImageView(){
        // 设置头像圆角
        var bounds = self.userImageView.bounds
        bounds.size.height -= 4
        bounds.size.width -= 4
        bounds.origin.x += 1
        bounds.origin.y += 1
        // Add rounded corners
       let maskLayer = CAShapeLayer()
       maskLayer.frame = bounds//self.AutorImageView.bounds
        maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 20).cgPath
        self.userImageView.layer.mask = maskLayer
        
       // Add border
       let borderLayer = CAShapeLayer()
       borderLayer.path = maskLayer.path // Reuse the Bezier path
        borderLayer.fillColor = UIColor.clear.cgColor
       borderLayer.strokeColor = UIColor.lightGray.cgColor
        borderLayer.lineWidth = 0.5
       borderLayer.frame = bounds
        self.userImageView.layer.addSublayer(borderLayer)
        
        if #available(iOS 13.0, *) {
            self.contentView.backgroundColor = Colors.backgroundColor
//            self.contentLabel.backgroundColor = Colors.backgroundColor
           
        } else {
            self.contentView.backgroundColor = .white
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }
    
    func generateEventAbstract(event: EventMdoel)-> NSAttributedString{
        
        let idStrAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorFromRGB(rgbValue: 0x0d6da8),NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
        
        let digestAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray,NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
        
        
        let digest = NSMutableAttributedString()
        let totalCommitsCount = Int(event.data["total_commits_count"] as? Int ?? 0)
        var digestsCount = 0
        
        while totalCommitsCount > 0 {
            // 获取提交数组
            if let commitsStr = event.data["commits"] as? [[String: Any]] {
                
                if let commitsModel = [CommitModel].deserialize(from: commitsStr) {
                    let commitid = commitsModel[digestsCount]!.id.suffix(9).description
                    let message = commitsModel[digestsCount]!.message ?? ""
                    let commitAutorName =  commitsModel[digestsCount]!.author.name.description
                    
                    let msg = " " + commitAutorName + " - " + message
                    digest.append(NSAttributedString(string: commitid, attributes: idStrAttributes))
                    digest.append(NSAttributedString(string: msg, attributes: digestAttributes))
                    
                    digestsCount += 1
                    if digestsCount == totalCommitsCount || digestsCount > 2 {break}
                    digest.append(NSAttributedString(string: "\n"))
                    
                }
            }
        }
        
        if totalCommitsCount > 2 {
            
            let moreCommitsNotice = "\n... and \(totalCommitsCount-2) more commits"
            digest.append(NSAttributedString(string: moreCommitsNotice, attributes: digestAttributes))
        }
        
        return digest
    }
    
    func setAbstractContent(event: EventMdoel){
        
        let actionType:actionEnum = actionEnum(rawValue: event.action!) ?? .DefaultUpdate
        let digestAttributes = [NSAttributedString.Key.foregroundColor: UIColor.darkGray,NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
        //
        var totalCommitsCount = 0
        if event.data != nil && event.data.count > 0 {
            totalCommitsCount = Int(event.data["total_commits_count"] as? Int ?? 0)
        }
        if totalCommitsCount > 0 {
            contentLabel.attributedText = generateEventAbstract(event: event)
        }
        else if actionType == actionEnum.COMMENTED {
            
            if let note = event.events.note {
                var comment = Tool.flattenHTML(note.note)
                comment = comment.count > 0 ? comment : ""
                comment = comment.trimmingCharacters(in: .newlines)
                
                contentLabel.attributedText = NSAttributedString(string: comment, attributes: digestAttributes)
            }
        }
        else if actionType == .MERGED {
            let content = event.eventContent()
            contentLabel.attributedText = NSAttributedString(string: content, attributes: digestAttributes)
        }
        else if actionType == .CREATED {
            var title = ""
            if event.target_type == "PullRequest" {
    
                if let reqModel = event.events.pullrequest {
                    title = reqModel.title
                }
               
            }else if event.target_type == "Issue" {
                
                if let issueM = event.events.issue {
                    title = issueM.title
                }
            }
            
            contentLabel.attributedText = NSAttributedString(string: title, attributes: digestAttributes)
        }else {
            
            contentLabel.attributedText = NSAttributedString(string: event.eventContent(), attributes: digestAttributes)
        }
        
    }
}

